/**
 * 
 */
package com.winit.openapi.fsp.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.fsp.spi.customer.CustomerService;
import com.winit.fsp.spi.customer.command.AnewCreateCustomerInfoCommand;
import com.winit.fsp.spi.customer.command.CreateCustomerInfoCommand;
import com.winit.fsp.spi.customer.command.GetCustomerInfoCommand;
import com.winit.fsp.spi.customer.command.UpdateCustomerInfoCommand;
import com.winit.fsp.spi.customer.vo.Customer;
import com.winit.fsp.spi.customer.vo.CustomerFile;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;

/**
 * fsp 资信处理
 * 
 * @author
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/fsp/customer")
public class FSPCustomerInfoController extends BaseController {

    @Resource
    private CustomerService customerService;

    /**
     * 申请客户资信
     * @param requestMsg
     * @param responseMsg
     * @return
     * @author BW 
     * @date 2015-3-11
     */
    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        CreateCustomerInfoCommand cCommand = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            cCommand = buildCreateCustomerInfoCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        CommandContext ctx = CommandContext.getContext();
        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        cCommand.setWinitPartnerName(bpartner.getName());
        cCommand.setWinitPartnerId(bpartner.getcBpartnerId());
        customerService.createCustomerInfo(cCommand);
        return SUCCESS;
    }

    /**
     * 重新申请客户资信
     * @param requestMsg
     * @param responseMsg
     * @return
     * @author BW 
     * @date 2015-3-11
     */
    @RequestMapping(value="/anewCreate")
    public String anewCreate(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        Object obj = requestMsg.getData();
        AnewCreateCustomerInfoCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = buildAnewCreateCustomerInfoCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        CommandContext ctx = CommandContext.getContext();
        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        command.setWinitPartnerName(bpartner.getName());
        command.setWinitPartnerId(bpartner.getcBpartnerId());
        customerService.anewCreateCustomerInfo(command);
        return SUCCESS;
    }
    
    /**
     * 修改fsp资信申请
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/update")
    public String update(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        UpdateCustomerInfoCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = buildUpdateCustomerInfoCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口更新信息
        customerService.updateCustomerInfo(command);

        return SUCCESS;
    }

    /**
     * 查询fsp资信详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GetCustomerInfoCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = buildQueryCustomerInfoCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        Customer customer = customerService.getCustomerInfo(command);
        if (customer != null) {
            Map<String, Object> data = buildReturnCustomerMap(customer);
            responseMsg.setData(data);
        }

        return SUCCESS;
    }

    private Map<String, Object> buildReturnCustomerMap(Customer customer) {
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        map.put("customerId", customer.getId());
        map.put("accountNo", customer.getAccountNo());
        map.put("creditLimit", customer.getCreditLimit());
        map.put("availableCreditLimit", customer.getAvailableCreditLimit());
        map.put("bank", customer.getBank());
        map.put("bankAddress", customer.getBankAddress());
        map.put("customerAddress", customer.getCustomerAddress());
        map.put("customerNameCn", customer.getCustomerNameCn());
        map.put("customerNameEn", customer.getCustomerNameEn());
        map.put("status", customer.getStatus());
        map.put("suggestion", customer.getSuggestion());
        map.put("swift", customer.getSwift());
        map.put("winitPartnerName", customer.getWinitPartnerName());
        map.put("created", df.format(customer.getCreated()));
        map.put("currency", customer.getCurrency());
        map.put("countries", customer.getCountries());
        map.put("region", customer.getRegion());
        map.put("legalPerson", customer.getLegalPerson());
        map.put("CFO", customer.getCFO());
        map.put("companyControl", customer.getCompanyControl());
        String establishDate="";
        if(customer.getEstablishDate()!=null ){
            establishDate=df.format(customer.getEstablishDate());
            map.put("establishDate", establishDate);
        } 
        map.put("overseasTel", customer.getOverseasTel());
        map.put("registerNo", customer.getRegisterNo());
        map.put("taxNo", customer.getTaxNo());
        map.put("exportGood", customer.getExportGood());
        map.put("customerFileList", customer.getCustomerFileList());
        Date tDate=DateUtil.getDate(customer.getUpdated(), 15); 
        String resultDate=df.format(tDate); 
        map.put("resultDate", resultDate);
        return map;
    }

     
    private GetCustomerInfoCommand buildQueryCustomerInfoCommand(JSONObject json) {
        GetCustomerInfoCommand command = new GetCustomerInfoCommand();
        if (json.containsKey("winitPartnerId")) {
            command.setWinitPartnerId(json.getString("winitPartnerId"));
        }
        return command;
    }
    
    private CreateCustomerInfoCommand buildCreateCustomerInfoCommand(JSONObject json) {
        CreateCustomerInfoCommand command = new CreateCustomerInfoCommand();
        if (json.containsKey("customerNameCn")) {
            command.setCustomerNameCn(json.getString("customerNameCn"));
        }
        if (json.containsKey("customerNameEn")) {
            command.setCustomerNameEn(json.getString("customerNameEn"));
        }
        if (json.containsKey("customerAddress")) {
            command.setCustomerAddress(json.getString("customerAddress"));
        }
        if (json.containsKey("accountNo")) {
            command.setAccountNo(json.getString("accountNo"));
        }
        if (json.containsKey("bank")) {
            command.setBank(json.getString("bank"));
        }
        if (json.containsKey("bankAddress")) {
            command.setBankAddress(json.getString("bankAddress"));
        }
        if (json.containsKey("swift")) {
            command.setSwift(json.getString("swift"));
        }
        if (json.containsKey("winitPartnerId")) {
            command.setWinitPartnerId(json.getLong("winitPartnerId"));
        }
        if (json.containsKey("winitPartnerName")) {
            command.setWinitPartnerName(json.getString("winitPartnerName"));
        }
        if (json.containsKey("country")) {
            command.setCountries(json.getString("country"));
        }
        if (json.containsKey("region")) {
            command.setRegion(json.getString("region"));
        }
        if (json.containsKey("legalPerson")) {
            command.setLegalPerson(json.getString("legalPerson"));
        }
        if (json.containsKey("establishDate")) {
            command.setEstablishDate(json.getDate("establishDate"));
        }
        if (json.containsKey("overseasTel")) {
            command.setOverseasTel(json.getString("overseasTel"));
        }
        if (json.containsKey("registerNo")) {
            command.setRegisterNo(json.getString("registerNo"));
        }
        if (json.containsKey("taxNo")) {
            command.setTaxNo(json.getString("taxNo"));
        }
        if (json.containsKey("exportGood")) {
            command.setExportGood(json.getString("exportGood"));
        }
        if (json.containsKey("CFO")) {
            command.setCFO(json.getString("CFO"));
        }
        if (json.containsKey("companyControl")) {
            command.setCompanyControl(json.getString("companyControl"));
        }
        if(json.containsKey("customerFileList")){
            List<CustomerFile> customerFileList=new ArrayList<CustomerFile>();
            JSONArray packageList = json.getJSONArray("customerFileList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                CustomerFile  customerFile= new CustomerFile();
                if (pack.containsKey("fileAddr")) {
                    customerFile.setFileAddr(pack.getString("fileAddr"));
                }
                if (pack.containsKey("fileType")) {
                    customerFile.setFileType(pack.getString("fileType"));
                } 
                customerFile.setWinitPartnerId(json.getLong("winitPartnerId"));
                customerFileList.add(customerFile);
            }
            command.setCustomerFileList(customerFileList);
        }
        return command;
    }

    private UpdateCustomerInfoCommand buildUpdateCustomerInfoCommand(JSONObject json) {
        UpdateCustomerInfoCommand command = new UpdateCustomerInfoCommand();

        if (json.containsKey("processInstanceId")) {
            command.setProcessInstanceId(json.getString("processInstanceId"));
        }
        if (json.containsKey("winitPartnerId")) {
            command.setWinitPartnerId(json.getLong("winitPartnerId"));
        }
        if (json.containsKey("customerNameEn")) {
            command.setCustomerNameEn(json.getString("customerNameEn"));
        }
        if (json.containsKey("customerAddress")) {
            command.setCustomerAddress(json.getString("customerAddress"));
        }
        if (json.containsKey("accountNo")) {
            command.setAccountNo(json.getString("accountNo"));
        }
        if (json.containsKey("bank")) {
            command.setBank(json.getString("bank"));
        }
        if (json.containsKey("bankAddress")) {
            command.setBankAddress(json.getString("bankAddress"));
        }
        if (json.containsKey("swift")) {
            command.setSwift(json.getString("swift"));
        }
        if (json.containsKey("creditLimit")) {
            command.setCreditLimit(json.getBigDecimal("CreditLimit"));
        }
        return command;
    }
    
    private AnewCreateCustomerInfoCommand buildAnewCreateCustomerInfoCommand(JSONObject json) {
        AnewCreateCustomerInfoCommand command = new AnewCreateCustomerInfoCommand();

        if (json.containsKey("customerNameCn")) {
            command.setCustomerNameCn(json.getString("customerNameCn"));
        }
        if (json.containsKey("customerNameEn")) {
            command.setCustomerNameEn(json.getString("customerNameEn"));
        }
        if (json.containsKey("customerAddress")) {
            command.setCustomerAddress(json.getString("customerAddress"));
        }
        if (json.containsKey("accountNo")) {
            command.setAccountNo(json.getString("accountNo"));
        }
        if (json.containsKey("bank")) {
            command.setBank(json.getString("bank"));
        }
        if (json.containsKey("bankAddress")) {
            command.setBankAddress(json.getString("bankAddress"));
        }
        if (json.containsKey("swift")) {
            command.setSwift(json.getString("swift"));
        }
        if (json.containsKey("winitPartnerId")) {
            command.setWinitPartnerId(json.getLong("winitPartnerId"));
        }
        if (json.containsKey("country")) {
            command.setCountries(json.getString("country"));
        }
        if (json.containsKey("region")) {
            command.setRegion(json.getString("region"));
        }
        if (json.containsKey("legalPerson")) {
            command.setLegalPerson(json.getString("legalPerson"));
        }
        if (json.containsKey("establishDate")) {
            command.setEstablishDate(json.getDate("establishDate"));
        }
        if (json.containsKey("overseasTel")) {
            command.setOverseasTel(json.getString("overseasTel"));
        }
        if (json.containsKey("registerNo")) {
            command.setRegisterNo(json.getString("registerNo"));
        }
        if (json.containsKey("taxNo")) {
            command.setTaxNo(json.getString("taxNo"));
        }
        if (json.containsKey("exportGood")) {
            command.setExportGood(json.getString("exportGood"));
        }
        if (json.containsKey("CFO")) {
            command.setCFO(json.getString("CFO"));
        }
        if (json.containsKey("companyControl")) {
            command.setCompanyControl(json.getString("companyControl"));
        }
        if(json.containsKey("customerFileList")){
            List<CustomerFile> customerFileList=new ArrayList<CustomerFile>();
            JSONArray packageList = json.getJSONArray("customerFileList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                CustomerFile  customerFile= new CustomerFile();
                if (pack.containsKey("fileAddr")) {
                    customerFile.setFileAddr(pack.getString("fileAddr"));
                }
                if (pack.containsKey("fileType")) {
                    customerFile.setFileType(pack.getString("fileType"));
                } 
                if(pack.containsKey("id")){
                    customerFile.setId(pack.getLong("id"));
                }
                customerFile.setWinitPartnerId(json.getLong("winitPartnerId"));
                customerFileList.add(customerFile);
            }
            command.setCustomerFileList(customerFileList);
        }
        return command;
    }
}
